<template>
  <div>
    <el-row gutter="20">
      <el-col :span="12">
        <el-card class="sur-card">
          <div class="sur-card-title" slot="header">
            <span>店铺设置</span>
          </div>
          <el-form
            :model="shopConfig"
            label-position="left"
            label-width="120px"
          >
            <el-form-item label="基础运费">
              <el-input-number
                precision="2"
                v-model="shopConfig.expressFee"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="免邮条件">
              <el-input-number
                precision="2"
                :min="0.0"
                :max="9999"
                v-model="shopConfig.freeExpQuota"
              ></el-input-number>
              <div class="hint-text">
                订单实付金额大于该金额将享受免邮,若为0即表示店铺所有商品免邮
              </div>
            </el-form-item>
            <el-form-item label="返佣比例">
              <el-input-number
                v-model="shopConfig.rewardRatio"
                precision="2"
                :min="0.0"
                :max="0.8"
                :step="0.01"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="开屏弹窗">
              <el-switch v-model="shopConfig.showCouponAd"></el-switch>
            </el-form-item>
            <el-form-item label="开屏优惠券图片">
              <el-upload
                style="display: inline-block;"
                :http-request="handleCouponImgUploadFile"
                :show-file-list="false"
              >
                <el-button size="small" type="primary" icon="el-icon-picture"
                  >点击上传</el-button
                >
              </el-upload>
              <el-image
                style="margin-top: 10px;height: 100px;width: 100px;display: flex;justify-content: center;"
                v-if="shopConfig.couponAdImgUrl"
                :preview-src-list="Array.of(shopConfig.couponAdImgUrl)"
                shape="square"
                fit="contain"
                :src="shopConfig.couponAdImgUrl"
              ></el-image>
              <div class="hint-title">
                <!--              建议尺寸长305px*宽305px，否则可能会变形-->
              </div>
            </el-form-item>
            <el-form-item label="开屏优惠券ID">
              <el-input v-model="shopConfig.adCouponId"></el-input>
            </el-form-item>
            <el-form-item label="分享文案">
              <el-input
                v-model="shopConfig.shareTexts"
                rows="5"
                type="textarea"
              >
              </el-input>
              <div class="hint-text">文案可以多个，以 | 符号隔开</div>
            </el-form-item>
            <el-form-item label="分享海报">
              <el-upload
                style="display: inline-block;"
                :http-request="handleShareImgUpload"
                :show-file-list="false"
              >
                <el-button size="small" type="primary" icon="el-icon-picture"
                  >点击上传</el-button
                >
              </el-upload>
              <div style="">
                <span v-for="(img, index) in shareImages" :key="index">
                  <hover-mask>
                    <!-- 默认插槽 -->
                    <el-image
                      :src="img"
                      fit="contain"
                      style="height: 160px;width: 100px;"
                    ></el-image>
                    <!-- action插槽 -->
                    <template v-slot:action>
                      <i
                        class="el-icon-delete"
                        @click="onDeleteShareImage(index)"
                      ></i>
                    </template>
                  </hover-mask>
                </span>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button
                type="danger"
                @click="onSaveShopConfig"
                style="width: 220px;"
                >保存</el-button
              >
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="sur-card">
          <div class="sur-card-title" slot="header">
            <span>首页轮播设置</span>
            <el-button type="text" @click="onAddBanner">添加</el-button>
          </div>
          <el-table :data="indexBanners" size="small" border>
            <el-table-column label="序号" type="index" align="center" />
            <el-table-column label="图片" align="center">
              <template slot-scope="scope">
                <el-image
                  :src="scope.row.imagePath"
                  style="height: 100px;"
                  fit="contain"
                  :preview-src-list="Array.of(scope.row.imagePath)"
                />
              </template>
            </el-table-column>
            <el-table-column label="是否显示" align="center">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.visible" disabled></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="链接类型" prop="jumpType" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.jumpType === 0">站内链接</span>
                <span v-if="scope.row.jumpType === 1">站外连接</span>
              </template>
            </el-table-column>
            <el-table-column label="链接地址" align="center">
              <template slot-scope="scope">
                <a :href="scope.row.jumpLink">{{ scope.row.jumpLink }}</a>
              </template>
            </el-table-column>
            <el-table-column label="排序" prop="sort" align="center">
            </el-table-column>
            <el-table-column
              label="说明"
              prop="memo"
              align="center"
              show-overflow-tooltip
            >
            </el-table-column>
            <!--            <el-table-column label="备注" prop="memo"> </el-table-column>-->
            <el-table-column label="操作" align="center" width="200">
              <template slot-scope="scope">
                <el-button-group>
                  <el-button
                    type="primary"
                    @click="onEditBanner(scope.row)"
                    size="small"
                    >编辑
                  </el-button>
                  <el-button
                    type="danger"
                    @click="deleteIndexBanner(scope.row)"
                    size="small"
                    >删除
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      :visible.sync="addBannerDiaVisible"
      title="首页图片链接设置"
      class="dialog"
      width="50%"
    >
      <div class="dialog-body">
        <el-form :model="bannerModel" label-width="100px" label-position="left">
          <el-form-item label="上传图片">
            <el-upload
              style="display: inline-block;"
              :http-request="handleImgUploadFile"
              :show-file-list="false"
            >
              <el-button size="small" type="primary" icon="el-icon-picture"
                >点击上传</el-button
              >
            </el-upload>
            <el-avatar
              style="margin-top: 10px;height: 100px;width: 100px;display: flex;justify-content: center;"
              v-if="bannerModel.imagePath"
              shape="square"
              size="100"
              fit="contain"
              :src="bannerModel.imagePath"
            ></el-avatar>
            <div class="hint-title">
              <!--              建议尺寸长305px*宽305px，否则可能会变形-->
            </div>
          </el-form-item>
          <el-form-item label="是否显示">
            <el-switch v-model="bannerModel.visible"></el-switch>
          </el-form-item>
          <el-form-item label="链接类型">
            <el-select v-model="bannerModel.jumpType">
              <el-option label="站内链接" :value="0"></el-option>
              <el-option label="站外链接" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="链接地址">
            <el-input
              v-model="bannerModel.jumpLink"
              placeholder="请输入图片点击后跳转的地址,可不填"
            ></el-input>
          </el-form-item>
          <el-form-item label="排序">
            <el-input-number
              controls-position="right"
              v-model="bannerModel.sort"
              :step="1"
              :min="0"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" row="3" v-model="bannerModel.memo" />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addBannerDiaVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSaveBanner">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getShopConfig,
  saveShopConfig,
  updateShopConfig
} from "@/api/admin-api/ShopConfigApi";
import HoverMask from "@/components/HoverMask";

import {
  addShopBanner,
  deleteShopBanner,
  getShopBanners,
  updateShopBanner
} from "@/api/admin-api/ShopLinkApi";
import {
  getUploadItemMediaToken,
  uploadFileToAliOss
} from "@/api/admin-api/FileApi";

export default {
  name: "ExpressSetting",
  components: {
    HoverMask
  },
  data() {
    return {
      shareImages: [],
      bannerModel: {
        imagePath: "",
        sort: 1,
        jumpLink: "",
        jumpType: 0,
        visible: false,
        memo: ""
      },
      indexBanners: [],
      shopConfig: {
        expressFee: 0.0,
        freeExpQuota: 0.0,
        showCouponAd: false,
        adCouponId: "",
        rewardRatio: 0,
        couponAdImgUrl: "",
        shareTexts: "",
        shareImages: ""
      },
      addBannerDiaVisible: false
    };
  },
  methods: {
    onDeleteShareImage(index) {
      this.shareImages.splice(index, 1);
    },
    handleCouponImgUploadFile({ file }) {
      getUploadItemMediaToken().then(uploadToken => {
        // 上传文件
        const formData = new FormData();
        const fileKey = uploadToken.dir.concat(file.name);
        formData.append("key", fileKey);
        formData.append("policy", uploadToken.policy);
        formData.append("OSSAccessKeyId", uploadToken.ossAccessKeyId);
        formData.append("success_action_status", "200");
        formData.append("signature", uploadToken.signature);
        formData.append("file", file);
        // 上传至阿里云oss
        this.$loading();
        console.log("上传地址", uploadToken.fileHost);
        uploadFileToAliOss(uploadToken.fileHost, formData)
          .then(() => {
            this.shopConfig.couponAdImgUrl =
              "https://asset.fanghaowu.com/" + fileKey;
            this.$loading().close();
          })
          .catch(() => {
            this.$loading().close();
          });
      });
    },
    async handleShareImgUpload({ file }) {
      const imgUrl = await this.uploadImgToOss(file);
      console.log("hhhahhimgUrl", imgUrl);
      this.shareImages.push(imgUrl);
      console.log("this.shopConfig.shareImages", this.shareImages);
    },
    async uploadImgToOss(file) {
      //获取上传的token ，并上传文件，返回文件地址
      return new Promise(resolve => {
        this.$loading();
        getUploadItemMediaToken()
          .then(policy => {
            // 上传到阿里云
            const formData = new FormData();
            const fileKey = policy.dir.concat(file.name);
            formData.append("key", fileKey);
            // formData.append('name', file.name)
            formData.append("policy", policy.policy);
            formData.append("OSSAccessKeyId", policy.ossAccessKeyId);
            formData.append("success_action_status", "200");
            // formData.append('callback', '')
            formData.append("signature", policy.signature);
            formData.append("file", file);
            uploadFileToAliOss(policy.fileHost, formData).then(() => {
              resolve(policy.fileHost + fileKey);
              this.$loading().close();
            });
          })
          .catch(() => {
            this.$loading().close();
          });
        this.$loading().close();
      });
    },
    async handleImgUploadFile({ file }) {
      this.bannerModel.imagePath = await this.uploadImgToOss(file);
    },
    onEditBanner(row) {
      this.bannerModel = row;
      this.addBannerDiaVisible = true;
    },
    deleteIndexBanner(row) {
      this.$confirm("确定要删除吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      }).then(() => {
        deleteShopBanner(row.id).then(() => {
          this.$message.success("操作成功");
          this.loadIndexBanners();
        });
      });
    },
    onSaveBanner() {
      this.$loading();
      if (this.bannerModel.id) {
        updateShopBanner(this.bannerModel).then(() => {
          this.$message.success("操作成功");
          this.loadIndexBanners();
          this.$loading().close();
        });
      } else {
        addShopBanner(this.bannerModel).then(() => {
          this.loadIndexBanners();
          this.$message.success("添加成功");
          this.$loading().close();
        });
      }
      this.addBannerDiaVisible = false;
    },
    onAddBanner() {
      this.bannerModel = this.$options.data().bannerModel;
      this.addBannerDiaVisible = true;
    },
    onSaveShopConfig() {
      this.shopConfig.shareImages = this.shareImages.join(",");
      if (this.shopConfig.id) {
        updateShopConfig(this.shopConfig).then(() => {
          this.$message.success("操作成功");
          this.loadShopConfig();
        });
      } else {
        saveShopConfig(this.shopConfig).then(() => {
          this.$message.success("操作成功");
          this.loadShopConfig();
        });
      }
    },
    loadShopConfig() {
      getShopConfig().then(data => {
        if (data) {
          this.shopConfig = data;
          if (data.shareImages) {
            this.shareImages = data.shareImages.split(",");
          }
        }
      });
    },
    loadIndexBanners() {
      getShopBanners({ size: 300, current: 1 }).then(data => {
        this.indexBanners = data.records;
      });
    }
  },
  mounted() {
    this.loadShopConfig();
    this.loadIndexBanners();
  }
};
</script>

<style scoped></style>
